import requests
from datetime import datetime
from app import db
from app.models import CollectLog

class BaseCollector:
    def __init__(self, fund_type):
        self.fund_type = fund_type
        self.headers = {
            'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/134.0.0.0 Safari/537.36 Edg/134.0.0.0'
        }

    def fetch_data(self, url):
        try:
            response = requests.get(url, headers=self.headers, timeout=10)
            response.raise_for_status()  # 检查请求是否成功
            data = response.json()
            return data
        except Exception as e:
            self.log_error(url, str(e))
            raise

    def log_success(self, url, count):
        log = CollectLog(
            fund_type=self.fund_type,
            api_url=url,
            status='success',
            count=count,
            error=''
        )
        db.session.add(log)
        db.session.commit()

    def log_error(self, url, error):
        log = CollectLog(
            fund_type=self.fund_type,
            api_url=url,
            status='fail',
            count=0,
            error=str(error)
        )
        db.session.add(log)
        db.session.commit()